<template xmlns="http://www.w3.org/1999/html">
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>设计API</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :inline="true" class="user-search">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getTableInfo()">搜索</el-button>
        <el-button size="small" type="success" icon="el-icon-success" @click="handleAdd()" :loading="isSyncing">保存
        </el-button>
        <el-button size="small" type="warning" icon="el-icon-success" @click="handleToApi()" :loading="isSyncing">
          生成接口
        </el-button>
        <el-button size="small" type="warning" icon="el-icon-success" @click="handleToSaveAs()" :loading="isSyncing">
          生成别名
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中" @cell-dblclick="editRow"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection">
      </el-table-column>
      <el-table-column align="center" prop="tableName" label="表名">
        <template slot-scope="scope">
          <span>{{ scope.row.tableName + "(" + scope.row.tableDesc + ")" }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="columnName" label="列名">
      </el-table-column>
      <el-table-column align="center" prop="descript" label="中文">
      </el-table-column>

      <el-table-column align="center" prop="columnSaveAs" label="别名">
      </el-table-column>
      <el-table-column align="center" prop="tbDict.dictName" label="字典">
      </el-table-column>

      <el-table-column align="center" prop="columnType" label="列属性">
      </el-table-column>
    </el-table>


    <el-dialog :title="'生成接口'" :visible.sync="buildFormVisible" @click='buildFormVisible = false' width="60%">
      <el-row>
        <el-button size="small" type="primary" icon="el-icon-search" @click="addNewApiForm()">新增</el-button>
      </el-row>
      <br/>
      <el-table size="small" :data="apiList" highlight-current-row border
                element-loading-text="拼命加载中"
                style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
        <el-table-column align="center" prop="requestName" label="请求名称" width="120">
        </el-table-column>
        <el-table-column align="center" prop="requestUrl" label="请求地址">
        </el-table-column>
        <el-table-column align="center" prop="requestMethod" label="请求方式" width="100">
        </el-table-column>
        <el-table-column align="center" prop="requestParams" label="参数" width="100">
        </el-table-column>
        <el-table-column align="center" prop="id" label="是否保存" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.id > 0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

    <el-drawer
      title="新增API"
      :visible.sync="drawer"
      :before-close="handleClose">
      <div>
        <el-form label-width="100px" ref="addForm" :model="addForm" :rules="rules">
          <el-form-item label="请求名称" prop="requestName">
            <el-input size="small" v-model="addForm.requestName" auto-complete="off" placeholder="请输入请求名称"/>
          </el-form-item>
          <el-form-item label="请求地址" prop="requestUrl">
            <el-input size="small" v-model="addForm.requestUrl" auto-complete="off" placeholder="请输入请求地址"/>
          </el-form-item>
          <el-form-item label="请求方式" prop="requestMethod">
            <el-select size="small" v-model="addForm.requestMethod" placeholder="请输入请求方式">
              <el-option v-for="type in ['POST', 'GET', 'PUT', 'DELETE']" :label="type" :value="type"
                         :key="type"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型" prop="requestParams">
            <el-select size="small" v-model="addForm.requestParams" placeholder="请选择参数类型">
              <el-option v-for="type in ['JSON(Filter)', 'JSON']" :label="type" :value="type" :key="type"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-button size="small" type="cancel" :loading="loading" class="title" @click="drawer = false">取消
              </el-button>
              <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('addForm')">
                保存
              </el-button>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-dialog
      title="修改"
      :visible.sync="dialogVisible"
      width="50%">
      <el-form ref="form" label-width="50px">
        <el-form-item label="别名">
          <el-input v-model="currentRow.columnSaveAs"></el-input>
        </el-form-item>
        <el-form-item label="字典">
          <el-select
            v-model="currentRow.dictType"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteSelectDictMethod"
            :loading="loading">
            <el-option
              v-for="item in dictOptions"
              :key="item.id"
              :label="item.dictName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddTem()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import {apiAdd, apiEdit, apiList, columnList, columnsSave, dictList} from "../../../api/baseMG";
import Pagination from '../../../components/Pagination'

export default {
  data() {
    return {
      list: [],
      drawer: false,
      apiList: [],
      loading: false,
      isSyncing: false,
      buildFormVisible: false,
      dialogVisible: false,
      addForm: {},
      currentCell: {},
      currentRow: {},
      defaultAPI: [],
      dictOptions: [],
      rules: {
        requestName: [
          {required: true, message: '请输入请求名称', trigger: 'blur'}
        ],
        requestUrl: [
          {required: true, message: '请输入请求地址', trigger: 'blur'}
        ],
        requestMethod: [
          {required: true, message: '请输入请求方式', trigger: 'blur'}
        ],
        requestParams: [
          {required: true, message: '请选择参数类型', trigger: 'blur'}
        ],
      }
    }
  },
  created() {
    this.getTableInfo();
  },
  components: {
    Pagination
  },
  methods: {
    remoteSelectDictMethod(query) {
      if (query !== '') {
        dictList({
          page: 1,
          perPage: 10,
          orderBy: "create_at desc",
          filters: [
            {
              showAble: true,
              readonly: false,
              placeholder: "字典名称",
              fieldName: "dictName",
              compare: "like",
              fieldValue: query
            }
          ]
        }).then(resp => {
          this.dictOptions = resp.data.list;
        })
      } else {
        this.options = [];
      }
    },
    editRow(row, cell) {
      if(row.tbDict) {
        this.dictOptions = [];

        this.dictOptions.push({
          id: row.dictType,
          dictName: row.tbDict.dictName
        })
      }
      console.log(row, cell);
      if(cell.label === '别名' || cell.label === '字典') {
        this.dialogVisible = true;
      }
      this.currentCell = cell;
      this.currentRow = row;
      let c = row.columnName;
      if(!this.currentRow.columnSaveAs) {
        this.currentRow.columnSaveAs = this.toCamelCase(c);
      }
    },
    selectAllApi() {
      apiList({
        page: 1,
        perPage: 10,
        filters: [
          {
            fieldName: "sourceId",
            compare: "=",
            fieldValue: this.$route.query.id
          },
          {
            fieldName: "schemaName",
            compare: "=",
            fieldValue: this.$route.query.schama
          },
          {
            fieldName: "tableName",
            compare: "=",
            fieldValue: this.$route.query.table
          },
        ]
      }).then(resp => {
        if (resp.success) {
          this.apiList = resp.data.list;
          let pageFlag = false;
          let addFlag = false;
          let updateFlag = false;
          let deleteFlag = false;

          this.apiList.forEach(item => {
            if (item.requestName === "分页查询") {
              pageFlag = true;
            }
            if (item.requestName === "单例新增") {
              addFlag = true;
            }
            if (item.requestName === "按主键修改") {
              updateFlag = true;
            }
            if (item.requestName === "按主键删除") {
              deleteFlag = true;
            }
          })
          if (!pageFlag) {
            this.apiList.push({
              requestName: "分页查询",
              requestUrl: "/WMCenter/safeguardService/" + this.$route.query.table + "/find",
              requestMethod: "POST",
              requestParams: "JSON(Filter)",
              id: null
            });
          }
          if (!addFlag) {
            this.apiList.push({
              requestName: "单例新增",
              requestUrl: "/WMCenter/safeguardService/" + this.$route.query.table + "/add",
              requestMethod: "POST",
              requestParams: "JSON",
              id: null
            });
          }
          if (!updateFlag) {
            this.apiList.push({
              requestName: "按主键修改",
              requestUrl: "/WMCenter/safeguardService/" + this.$route.query.table + "/update",
              requestMethod: "POST",
              requestParams: "JSON",
              id: null
            });
          }
          if (!deleteFlag) {
            this.apiList.push({
              requestName: "按主键删除",
              requestUrl: "/WMCenter/safeguardService/" + this.$route.query.table + "/delete",
              requestMethod: "POST",
              requestParams: "JSON",
              id: null
            })
          }
        }
      })
    },
    submitForm() {
      let that = this;
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          console.log(that.addForm)
          if (!that.addForm.id) {
            apiAdd(that.addForm).then(resp => {
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: resp.msg
                });
                this.drawer = false;
                this.selectAllApi();
              } else {
                this.$message({
                  type: 'error',
                  message: resp.msg
                });
              }
            })
          } else {
            apiEdit(that.addForm).then(resp => {
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: resp.msg
                });
                this.drawer = false;
                this.selectAllApi();
              } else {
                this.$message({
                  type: 'error',
                  message: resp.msg
                });
              }
            })
          }

        }
      });
    },
    handleEdit(index, row) {
      this.addForm = row;
      this.addForm.sourceId = this.$route.query.id;
      this.addForm.schemaName = this.$route.query.schama;
      this.addForm.tableName = this.$route.query.table;
      this.drawer = true;
    },
    initApiList() {
      this.apiList = [];
      this.selectAllApi();
    },
    handleClose() {
      this.drawer = false;
    },
    addNewApiForm() {
      this.addForm = {};
      this.drawer = true;
    },
    handleToApi() {
      this.initApiList();
      this.buildFormVisible = true;
    },
    handleToSaveAs() {
      for (const listKey in this.list) {
        if(!this.list[listKey].columnSaveAs) {
          console.log(this.list[listKey])
          this.list[listKey].columnSaveAs = this.toCamelCase(this.list[listKey].columnName);
        }
      }
    },
    getTableInfo() {
      let query = this.$route.query;
      columnList({id: query.id, schama: query.schama, tableName: query.table}).then(resp => {
        if (resp.success) {
          this.list = resp.data
        }
      });
    },
    handleAddTem() {
      this.dialogVisible = false;
      for (const listKey in this.list) {
        this.list[listKey].sourceId = this.$route.query.id;
        this.list[listKey].schemaName = this.$route.query.schama;
      }
    },
    handleAdd() {
      this.isSyncing = true;
      this.dialogVisible = false;
      for (const listKey in this.list) {
        this.list[listKey].sourceId = this.$route.query.id;
        this.list[listKey].schemaName = this.$route.query.schama;
      }
      columnsSave(this.list).then(resp => {
        this.isSyncing = false;
        if (resp.success) {
          this.$message({
            type: 'success',
            message: resp.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: resp.msg
          })
        }
      })
    },
    toCamelCase(str) {
      return str
        .replace(/[^a-z0-9]/gi, ' ')
        .toLowerCase()
        .split(' ')
        .map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length))
        .join('');
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
</style>
